import urllib.error

import dmhua8
import save_util

url = 'https://m.dmhua8.com/manhua/fanghuangzhemendezhongshengyouxi/'
start_chapter_num = 0

comic_name, chapter_urls = dmhua8.find_chapter_urls(url)
chapter_num = 0
for chapter_url_and_name in chapter_urls:
    chapter_num = chapter_num + 1
    if chapter_num < start_chapter_num:
        continue
    chapter_url = chapter_url_and_name[0]
    chapter_name = chapter_url_and_name[1]
    page_position = chapter_url.rindex('.')
    page_url_1 = chapter_url[0:page_position]
    page_url_2 = chapter_url[page_position:]
    in_chapter = True
    page_num = 1
    img_index = 1
    while in_chapter:
        page_url = page_url_1 + '-' + str(page_num) + page_url_2
        print(page_url)
        img_urls = dmhua8.get_img_urls_from_page(page_url)
        page_num = page_num + 1
        if len(img_urls) > 0:
            for img_url in img_urls:
                try:
                    save_util.save_img(comic_name, chapter_name, str(img_index), img_url)
                    img_index = img_index + 1
                except urllib.error.HTTPError as e:
                    print(e)
                    print('request failed for: ' + img_url)
        else:
            in_chapter = False
